const spawn = require('child_process').spawn
const log = require('./log')
const iconv = require('iconv-lite')
const AU = require('ansi_up');
const ansi_up = new AU.default

const encoding = process.platform === 'win32' ? 'cp936' : 'utf8'
const binaryEncoding = 'binary'
const regex = /(<([^>]+)>)/ig
module.exports.cmdExec = function (cmd, ps, isPrint = false, needReturn = false) {

  log.info(`执行命令：${cmd} ${ps.join(" ")}`)
  return new Promise(function (resolve) {
    let resStr = ''
    log.info(`主进程id:${process.pid}`)
    const build = spawn(cmd, ps, {encoding: binaryEncoding})


    log.info(`子进程id:${build.pid}`)
    build.stdout.on('data', (data) => {
      let str = iconv.decode(Buffer.from(data, binaryEncoding), encoding)
      if (needReturn) resStr += ansi_up.ansi_to_html(str).replace(regex, "")
      isPrint && log.info(ansi_up.ansi_to_html(str).replace(regex, ""))
    })

    build.stderr.on('data', (error) => {
      let str = iconv.decode(Buffer.from(error, binaryEncoding), encoding)
      if (needReturn) resStr += str
      isPrint && log.error(str)
    })

    build.on('error', (error) => {
      console.log(error)
    })

    build.on('close', () => {
      log.info('cmd close')
      resolve(resStr)
    })
  })
}
